<template>
  <div class="app-container taskEdit" style="display: flex; justify-content: center; padding: 40px; padding-left: 0px; padding-right: 140px;padding-top: 50px">
    <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules" style="width: 60%">
      <el-form-item label="考试标题：" prop="name"  required>
        <el-input v-model="form.name" placeholder="请输入考试标题"></el-input>
      </el-form-item>
      <el-form-item label="考试类型：" prop="examType">
        <el-select v-model="form.examType" filterable placeholder="请选择（或输入）考试类型">
          <el-option
            v-for="item in paperTp"
            :key="item.id"
            :label="item.name"
            :value="item.id"
            :title="item.name">
            <span>{{ item.name }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联试卷：" required>
        <el-checkbox-group 
          v-model="checkedPaperId"
          :min="1"
          :max="1">
          <el-checkbox v-for="item in paperList" :label="item.id" :key="item.id" value="item.id">{{ item.name }}</el-checkbox>
          <el-button type="text" class="link-left" style="margin-left: 16px; color: #09c214; font-size: 0.9rem; font-weight: 600;" size="mini" @click="checkedPaperId = []">
            重选
          </el-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="考试员工：" required>
        <dataTree
          class="tree-border"
          :data="empList"
          show-checkbox
          :default-expand-all="false"
          ref="empTree"
          node-key="id"
          :filter-node-method="filterNode"
          empty-text="加载中，请稍候"
          :props="defaultProps"
          @check-change="getTreeCheckedKeys"
          @node-click="handleNodeClick"
          :default-expanded-keys="treeExpandData"
          highlight-current
        />
      </el-form-item>
      <el-form-item style="margin-top: 60px; display: flex; justify-content: center;">
        <el-button plain @click="$router.push('/task/list')">取消</el-button>
        <el-button type="info" @click="resetForm">重置</el-button>
        <!-- <el-button type="success" @click="addPaper">添加试卷</el-button> -->
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>

    <el-dialog :visible.sync="paperPage.showDialog" width="70%">
      <el-form :model="paperPage.queryParam" ref="queryForm" :inline="true" style="display: flex; justify-content: center;">
        <el-form-item label="试卷名称：" >
          <el-input v-model="paperPage.queryParam.nameKeyword" placeholder="请输入试卷名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="examPaperSubmitForm" style="margin-left: 10px">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="paperPage.listLoading" :data="paperPage.tableData"
                @selection-change="handleSelectionChange" border fit highlight-current-row style="width: 100%">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="id" label="Id" width="100px"/>
        <el-table-column prop="subjectId" label="分类" :formatter="subjectFormatter" width="120px" />
        <el-table-column prop="name" label="名称"  />
        <el-table-column prop="createTime" label="创建时间" width="160px"/>
      </el-table>
      <pagination v-show="paperPage.total>0" :total="paperPage.total"
                  :page.sync="paperPage.queryParam.pageIndex" :limit.sync="paperPage.queryParam.pageSize"
                  @pagination="search"/>
      <span slot="footer" class="dialog-footer">
          <el-button @click="paperPage.showDialog = false">取 消</el-button>
          <el-button type="success" @click="confirmPaperSelect">确定</el-button>
     </span>
    </el-dialog>
  </div>
</template>

<script>
import taskApi from '@/api/task'
import examPaperApi from '@/api/examPaper'
import Pagination from '@/components/Pagination'
import { mapGetters, mapState, mapActions } from 'vuex'
import userApi from '@/api/user'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import dataTree from '@/components/tree/src/tree.vue'

export default {
  components: { Pagination, Treeselect, dataTree },
  data () {
    const generateData = _ => {
      const data = [];
      const cities = ['上海', '北京', '广州', '深圳', '南京', '西安', '成都'];
      const pinyin = ['shanghai', 'beijing', 'guangzhou', 'shenzhen', 'nanjing', 'xian', 'chengdu'];
      cities.forEach((city, index) => {
        data.push({
          label: city,
          key: index,
          pinyin: pinyin[index]
        });
      });
      return data;
    };
    return {
      treeExpandData: [],
      empList: [],
      data: generateData(),
      value: [],
      checkedPaperId: [],
      filterMethod(query, item) {
        return item.pinyin.indexOf(query) > -1;
      },
      paperItems: [],
      paperTp: [
        { id: 1, name: '固定考试' },
        { id: 4, name: '时段考试' }
      ],
      parentList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      categoryList: [],
      paperList: [],
      form: {
        id: undefined,
        name: undefined,
        examType: undefined,
        userIds: [],
        paperId: undefined
      },
      formLoading: false,
      paperPage: {
        subjectFilter: null,
        multipleSelection: [],
        showDialog: false,
        queryParam: {
          subjectId: null,
          level: null,
          paperType: 6,
          pageIndex: 1,
          pageSize: 5
        },
        listLoading: true,
        tableData: [],
        total: 0
      },
      rules: {
        name: [{ required: true, message: '请输入考试标题', trigger: ['blur'] }],
        // userIds: [
        //   { required: true, message: '请选择考试员工', trigger: ['blur','change'] }
        // ],
        // paperId: [
        //   { required: true, message: '请勾选关联试卷', trigger: ['blur','change'] }
        // ]
      },
    }
  },
  created () {
    let _this = this
    this.initSubject(function () {
      _this.paperPage.subjectFilter = _this.subjects
    })

    this.loadAll()
  },
  methods: {
    getRoleTreeRootNode(res) {
      this.treeExpandData.push(res[0].id)      
    },
    //加载修改树结构json
    findZNodes() {
      userApi.getUserDepartsTree().then(res => {
        this.empList = res.response
        this.getRoleTreeRootNode(res.response)
      })
    },
    // 根据当前获取的tree节点信息查找父节点
    getParent (node) {
      if(node.isLeaf == false && node.parent.parent == null){ //
          this.parentList.push(node.data);
      }else{
          if(node.isLeaf == false && node.parent.parent != null ){ //
            this.parentList.push(node.data);
            this.getParent(node.parent)
          }else if(node.isLeaf == true && node.parent.parent != null){
              this.parentList.push(node.data);
              this.getParent(node.parent)
          }
      }
    },
    handleNodeClick(item, node) {
      this.parentList = [];
      this.getParent(node);
    },
    // 共三个参数，依次为：1. 传递给 data 属性的数组中该节点所对应的对象、2. 节点本身是否被选中、3. 节点的子树中是否有被选中的节点
    getTreeCheckedKeys(data, checked) {
      let arr = this.$refs.empTree.getCheckedKeys()
      let newarr = []
      this.$refs.empTree.setCheckedKeys([])
      arr.forEach((item,index) => {
        if (typeof item ==  'string') {
          newarr.push(item)
          this.$refs.empTree.setChecked(item, true, false)
        } else {
          this.$refs.empTree.setChecked(item, false, false)
        }
      })
      // this.$refs.empTree.setCheckedKeys(newarr)
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    fuzzyqueryJob(e, input) {
      if (this.form.examType !== '' && this.form.examType !== null && this.form.examType !== undefined) {
        const jobParam = { keyword: this.form.examType + '' }
        taskApi.getTaskCategorys(jobParam).then(res => {
          this.categoryList = res.response
        })
        this.input = e.target.value
      }
    },
    createFilter(queryString) {
      return returnJobs => {
        return (
          returnJobs.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        )
      }
    },
    querySearch0(queryString, cb) {
      const categorylist = this.categoryList
      let results = queryString
        ? categorylist.filter(this.createFilter(queryString))
        : categorylist
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    loadAll() {
      let _this = this
      taskApi.getTaskCategorys().then(res => {
        this.categoryList = res.response
      })

      examPaperApi.pageList().then(res => {
        this.paperList = res.response.list
      })

      
      let id = this.$route.query.id
      if (id && parseInt(id) !== 0) {
        _this.formLoading = true
        
        taskApi.pageList({ examId: id }).then(data => {
          const re = data.response
          this.form = {
            id: re.list[0].examId,
            name: re.list[0].examName,
            examType: re.list[0].examType,
            paperId: this.checkedPaperId,
            userIds: []
          }
          _this.formLoading = false
        })

        // taskApi.editTask(id).then(re => {
        //   _this.form = re.response
        //   _this.formLoading = false
        // })
      }

      _this.findZNodes()
    },
    addPaper () {
      this.paperPage.queryParam.level = this.form.gradeLevel
      this.paperPage.showDialog = true
      this.search()
    },
    confirmPaperSelect () {
      this.paperPage.multipleSelection.forEach(ep => this.form.paperItems.push(ep))
      this.paperPage.showDialog = false
    },
    search () {
      this.paperPage.showDialog = true
      this.listLoading = true
      // examPaperApi.taskExamPage(this.paperPage.queryParam).then(data => {
      examPaperApi.pageList(this.paperPage.queryParam).then(data => {
        const re = data.response
        this.paperPage.tableData = re.list
        this.paperItems = re.list
        this.paperPage.total = re.total
        this.paperPage.queryParam.pageIndex = re.pageNum
        this.paperPage.listLoading = false
      })
    },
    handleSelectionChange (val) {
      this.paperPage.multipleSelection = val
    },
    examPaperSubmitForm () {
      this.paperPage.queryParam.pageIndex = 1
      this.search()
    },
    levelChange () {
      this.paperPage.queryParam.subjectId = null
      this.paperPage.subjectFilter = this.subjects.filter(data => data.level === this.form.gradeLevel)
    },
    removePaper (row) {
      this.form.paperItems.forEach((item, index, arr) => {
        if (item.id === row.id) {
          arr.splice(index, 1)
        }
      })
    },
    submitForm () {
      let _this = this
      this.form.userIds = this.$refs.empTree.getCheckedKeys()
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.checkedPaperId.length == 0) {
            _this.$message.error('请勾选关联试卷!')
            return
          }
          if (_this.$refs.empTree.getCheckedKeys().length == 0) {
            _this.$message.error('请勾选考试员工!')
            return
          }
          this.form.paperId = this.checkedPaperId[0]
          this.formLoading = true
          taskApi.editTask(this.form).then(data => {
            if (data.code === 1) {
              _this.$message.success(data.message)
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/task/list')
              })
            } else {
              _this.$message.error(data.message)
              _this.$refs.empTree.setCheckedKeys([])
              _this.formLoading = false
              _this.findZNodes()
            }
            _this.formLoading = false
          }).catch(e => {
            _this.$refs.empTree.setCheckedKeys([])
            _this.formLoading = false
            _this.findZNodes()
          })
        } else {
          return false
        }
      })
    },
    resetForm () {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        id: undefined,
        name: undefined,
        examType: undefined,
        userIds: [],
        paperId: undefined
      }
      this.$refs.empTree.setCheckedKeys([])
      this.form.id = lastId
      this.findZNodes()
    },
    subjectFormatter (row, column, cellValue, index) {
      return this.subjectEnumFormat(cellValue)
    },
    ...mapActions('exam', { initSubject: 'initSubject' }),
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionTypeEnum: state => state.exam.question.typeEnum,
      levelEnum: state => state.user.levelEnum
    }),
    ...mapGetters('exam', ['subjectEnumFormat']),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>

<style rel="stylesheet/scss" lang='scss'>
  .taskEdit .el-autocomplete {
    position: relative;
    display: inline-block;
    width: 100%;
  }
  
  .taskEdit .el-select {
    display: inline-block;
    position: relative;
    width: 100%;
  }
  
  .taskEdit .el-form-item__error {
    color: #ff4949;
    font-size: 12px;
    line-height: 1;
    padding-top: 0px;
    position: absolute;
    top: 100%;
    left: 0;
  }

  .taskEdit .el-dialog {
    -webkit-transform: none;
    transform: none;
    left: 0;
    position: relative;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  .taskEdit .el-dialog__body {
    padding: 49px 20px;
    color: #606266;
    font-size: 14px;
    width: 90%;
    word-break: break-all;
  }

  .taskEdit .pagination-container {
    background: #fff;
    text-align: center;
  }
  
  </style>